//
//  NetHelper.m
//  LoveHealth
//
//  Created by 陈永坤 on 14-9-28.
//  Copyright (c) 2014年 lanou. All rights reserved.
//

#import "NetHelper.h"
#import "Reachability.h"
#import <CommonCrypto/CommonDigest.h>
#import "KGStatusBar.h"

#define KDownloadDate @"DownloadDate"
#define kExpiresInSeconds @"ExpiresInSeconds"
#define kExpiryDate @"ExpiryDate"
#define kLocalURL @"LocalURL"

static NetHelper * helper = nil;

@interface NetHelper()
@property (nonatomic,retain)NSMutableDictionary * dataDic; //从本地读的dic
@property (nonatomic,retain)NSString * dataDicPath; //本地dic路径
@property (nonatomic,retain)NSString * dataPath; //data文件夹路径
@property (nonatomic,retain)NSFileManager * fileManager;
@property (nonatomic,assign)NetworkStatus status; //网络状态
@end
@implementation NetHelper


+ (NetHelper *)shareInstance
{
    if (!helper) {
        helper = [[NetHelper alloc]init];
        
        
        //缓存路径
        NSString * cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
        helper.dataPath = [cachesPath stringByAppendingPathComponent:@"data"];
        
        //缓存的字典路径
        helper.dataDicPath = [helper.dataPath stringByAppendingPathComponent:@"cacheData.dic"];
        
        //创建缓存路径
        helper.fileManager = [NSFileManager defaultManager];
        BOOL  result =  [helper.fileManager fileExistsAtPath:helper.dataPath];
        if (!result) {
            //先把空dic保存到本地
            [helper.fileManager createDirectoryAtPath:helper.dataPath withIntermediateDirectories:YES attributes:nil error:nil];
            NSMutableDictionary * dic = [NSMutableDictionary dictionary];
            [dic writeToFile:helper.dataDicPath atomically:YES];
        }
        //从本地dic读取到dataDic
        helper.dataDic = [NSMutableDictionary dictionaryWithContentsOfFile:helper.dataDicPath];
        
    }
    return helper;
}


- (void)loadingDataWithUrlString:(NSString *)urlString urlExpireInSeconds:(NSTimeInterval)timeInterval download:(DownloadBlock)download
{
    //网络
    AppDelegate *appDlg = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    NSParameterAssert([appDlg.hostReach isKindOfClass: [Reachability class]]);
    helper.status = [appDlg.hostReach currentReachabilityStatus];
    
    //计算请求网络url的哈希值，即是缓存文件名
    NSString * fileName = [[self class] SHA1WithStr:urlString];
    //缓存文件路径
    NSString * filePath = [self.dataPath stringByAppendingPathComponent:fileName];
    
    //判断网络
    if (self.status == NotReachable) {
        //无网络
//        UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:nil message:@"网络已断开" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
//        [alertView show];
//        [alertView release];
        
        [KGStatusBar showErrorWithStatus:@"网络连接错误"];
        NSLog(@"----无网络连接------");
        
        //判断文件是否存在
        if ([self.fileManager fileExistsAtPath:filePath]) {
            //从本地读取缓存文件
            NSData * readData = [NSData dataWithContentsOfFile:filePath];
            //block回调
            download(nil,readData,nil);
        }
    }else{
        
        //当前时间
        NSDate * now = [NSDate date];
        
        
        //从获取缓存字典里每一条缓存数据的小字典
        NSDictionary * readDic = self.dataDic[fileName];
        
        //读取缓存的过期时间
        NSDate * readExpiryDate = [readDic objectForKey:kExpiryDate];
        
        //判断缓存文件是否过期和存在
        if ([now timeIntervalSinceDate:readExpiryDate] < 0.0 &&[self.fileManager fileExistsAtPath:filePath]) {
            
            //本地缓存路径
            NSString * fileDataPath = [readDic objectForKey:kLocalURL];
            //读取数据
            NSData * data = [NSData dataWithContentsOfFile:fileDataPath];
            //block回调
            download(nil,data,nil);
            
        }else{
            //创建子线程
            dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
            
            dispatch_async(queue, ^{
                
                //设置网络请求
                NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
                //建立同步连接
                NSURLResponse * response = nil;
                NSError * error = nil;
                
                //从网络请求数据
                NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
                
                NSLog(@"%@",error);
                NSLog(@"%@",error.domain);
                NSLog(@"%ld",error.code);
                NSLog(@"%@",error.localizedDescription);
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    //如果请求到数据
                    if (data != nil && data.length ==[response expectedContentLength]) {
                        //创建一个每条数据的小字典
                        NSMutableDictionary * fileDic =[NSMutableDictionary dictionary];
                        //给每个键值对赋值
                        [fileDic setObject:[NSDate date] forKey:KDownloadDate];
                        [fileDic setObject:[NSNumber numberWithDouble:timeInterval] forKey:kExpiresInSeconds];
                        [fileDic setObject:[[NSDate date] dateByAddingTimeInterval:timeInterval]forKey:kExpiryDate];
                        [fileDic setObject:filePath forKey:kLocalURL];
                        //把小字典放到大字典里
                        [self.dataDic setObject:fileDic forKey:fileName];
                        //把大字典保存到本地
                        [self.dataDic writeToFile:self.dataDicPath atomically:YES];
                        //把请求到的数据缓存到本地
                        [data writeToFile:filePath atomically:YES];
                        
                    }
                    //block回调
                    download(response,data,error);
                });
            });
        }
        
    }

}

- (NSUInteger)cachesDataSize
{
    if (![self.fileManager fileExistsAtPath:self.dataPath]) {
        return 0;
    }
    NSEnumerator * childFilesEnumerator = [[self.fileManager subpathsAtPath:self.dataPath] objectEnumerator];
    NSString * fileName;
    NSUInteger folderSize = 0;
    while ((fileName = [childFilesEnumerator nextObject]) != nil) {
        NSString * fileAbsolutePath = [self.dataPath stringByAppendingPathComponent:fileName];
        folderSize += [[self.fileManager attributesOfItemAtPath:fileAbsolutePath error:nil] fileSize];
    }
    return folderSize;
}

- (void)cleanCachesData
{
    if ([self.fileManager fileExistsAtPath:self.dataPath]) {
        [self.fileManager removeItemAtPath:self.dataPath error:nil];
    }
}

- (void)dealloc
{
    self.dataDic = nil;
    self.dataPath = nil;
    self.fileManager = nil;
    [super dealloc];
}
/*
+(void)loadingDataWithUrlString:(NSString *)urlString download:(DownloadBlock)download
{
    AppDelegate *appDlg = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    NSParameterAssert([appDlg.hostReach isKindOfClass: [Reachability class]]);
   
    NetworkStatus status = [appDlg.hostReach currentReachabilityStatus];
    
    NSString * cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
    NSString * dataPath = [cachesPath stringByAppendingPathComponent:@"data"];
    
    
    NSFileManager * fileManager = [NSFileManager defaultManager];
    //判断文件是否存在， 参数:文件的完整的路径， 返回值是 BOOL
    BOOL  result =  [fileManager fileExistsAtPath:dataPath];
    if (!result) {
        [fileManager createDirectoryAtPath:dataPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    
    if (status == NotReachable) {
        
        NSLog(@"----无网络连接------");
        
        NSString * filePath = [dataPath stringByAppendingPathComponent:[self SHA1WithStr:urlString]];
        
        if ([fileManager fileExistsAtPath:filePath]) {
            NSData * readData = [NSData dataWithContentsOfFile:filePath];
            download(nil,readData,nil);
        }
    }else{
//     dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//        dispatch_async(queue, ^{
//            
//            NSURL * url = [NSURL URLWithString:urlString];
//            NSData * data = [NSData dataWithContentsOfURL:url];
//            
//            dispatch_async(dispatch_get_main_queue(), ^{
//                downloadSuccess(data);
//                
//            });
        
         [NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
             
             if (data != nil) {
                 NSString * filePath = [dataPath stringByAppendingPathComponent:[self SHA1WithStr:urlString]];
                 [data writeToFile:filePath atomically:YES];
             }
             download(response,data,connectionError);
         }];
        NSLog(@"----有网------");
        NSString * str = [self SHA1WithStr:urlString];
        NSLog(@"%@",str);
    }

}
*/
#pragma mark 使用SHA1加密字符串
+ (NSString *)SHA1WithStr:(NSString *)str
{
    const char *cStr = [str UTF8String];
    NSData *data = [NSData dataWithBytes:cStr length:str.length];
    uint8_t digest[CC_SHA1_DIGEST_LENGTH];
    
    CC_SHA1(data.bytes, (int)data.length, digest);
    
    NSMutableString *result = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
    
    for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++) {
        [result appendFormat:@"%02x", digest[i]];
    }
    
    return result;
}

@end
